package cn.softgame.jserver.application.connection;

import cn.softgame.jserver.application.Connection;
import cn.softgame.jserver.connector.tcp.TCPClient;
import cn.softgame.jserver.queue.QueueFactory;

/**
 * TCP连接，TCP连接比较稳定，没有丢包，但是速度比UDP低。
 * @author xuquan
 * 日期:2013-5-28
 */
public class TcpConnection extends Connection{
	private final static QueueFactory queueFactory = QueueFactory.getInstance();
	private TCPClient client=null;
	private boolean isConnect=false;
	
	/**
	 * 客户端连接初始化
	 * @param client
	 */
	public TcpConnection(TCPClient client){
		this();
		this.client=client;
		this.csType=ConnectionFactory.CLIENT;
	}
	
	/**
	 * 服务器端连接初始化
	 */
	public TcpConnection(){
		queue = queueFactory.getQueue(QueueFactory.TCP_QUEUE);
		this.csType=ConnectionFactory.TCPSERVER;
		isConnect=true;
	}

	@Override
	public void open(String url, int port) throws Exception {
		try {
			client.openSocketChannel(url,port);
			isConnect=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void close() throws Exception {
		if(!isConnect)
			return;
		try{
			client.close();
			isConnect=false;
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	@Override
	public boolean isConnect() throws Exception {
		return isConnect;
	}
	
}
